﻿CREATE PROCEDURE Security.SaveUser
@OID			        bigint,
@GUID                   varchar(64),
@FullName               varchar(128),
@UPN                   varchar(128)

AS 
BEGIN
	IF @OID = 0 BEGIN
		INSERT INTO dbo.Users
			( GUID, FullName, UPN, LastSignedIn, UpdatedDate, CreatedDate )
			VALUES ( @GUID, @FullName, @UPN, GetDate(), GetDate(), GetDate() )
		Select OID From Users Where OID = Scope_Identity()
	END
	ELSE BEGIN
		Update dbo.Users
			Set 
				GUID = @GUID,
				FullName = @FullName,
				UPN = @UPN,
				LastSignedIn = GetDate(),
				UpdatedDate = GetDate()
			Where
				OID = @OID

		IF @@ROWCOUNT = 0 
		BEGIN
			-- If no records were found (and updated) - it means that another process had updated 
			-- this record (therefore timestamp will be different) or record was deleted (OID not found)
			-- Either way, we need to raise exception
			RAISERROR(99999, 16, 1, 'User')
		END
		ELSE BEGIN 
			Select OID From Users Where OID = @OID
		END
	END
END